package com.dys.controller;

import com.dys.entity.CheckCode;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @Author: 疾风
 * @ClassName: KaptchaController
 * @Description: 生成验证码控制器
 * @CreateDate: 2024/12/18
 * @Version: v1.0.0
 */
@Controller
public class KaptchaController {

    private final Producer producer;

    @Autowired
    public KaptchaController(Producer producer) {
        this.producer = producer;
    }

    @GetMapping(value = "/code/image")
    public void getVerifyCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 1.创建验证码文本
        String codeText = producer.createText();

        // 2.创建验证码图片
        BufferedImage codeImage = producer.createImage(codeText);

        // 3.将验证码文本放进 Session 中,设置验证码的有效时间
        CheckCode checkCode = new CheckCode(codeText);
        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, checkCode);

        // 4.将验证码图片返回，禁止验证码图片缓存
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);

        // 5.设置ContentType
        response.setContentType("image/png");
        ImageIO.write(codeImage,"jpg",response.getOutputStream());
    }
}
